package view;

import model.OnScreen;

import com.vandorenmes.argusv6.R;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class ArgusActivity extends Activity 
{
	private static final String TAG = ArgusActivity.class.getSimpleName();

	private TextView _reconnectLbl;
	
	private Handler _toastHandler;
	private Toast _toast;

	//connected to server
	private boolean _connected;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		
		_toastHandler = new Handler();
		_toast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT);
	}
	
	public synchronized void makeToast(final int reconnect)
	{
		final String msg = getResources().getString(reconnect);
		
		_toastHandler.post(new Runnable() 
		{
			@Override
			public void run() 
			{	
				Log.d(TAG, String.format("makeToast - %s", msg));
				if(reconnect == R.string.connection_lost)
					handleErrorLabel(false);
				
				_toast.cancel();	// cancel previous toast			
				
				Log.e("TOAST", String.format("%s", msg));
				_toast = Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT);
				_toast.show();
			}
		});
		
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) 
	{			
		if(event.getAction() == MotionEvent.ACTION_DOWN)
		{
			if(!_connected)
			{
				Log.e("", String.format("Attempting to reconnect"));
				handleErrorLabel(true);
				OnScreen.getInstance().getWebServiceConnector().connectToServer(this);
				return true;
			}
			return super.onTouchEvent(event);
		}
		
		return false;
	}
	
	private void handleErrorLabel(boolean connected)
	{
		Log.d(TAG, String.format("HandleErrorLabel - %s - %s", connected, _reconnectLbl));
		_connected = connected;
		
		if(_reconnectLbl == null)
			_reconnectLbl = (TextView) findViewById(R.id.error_label);

		_reconnectLbl.setVisibility(_connected ? View.INVISIBLE : View.VISIBLE);
		_reconnectLbl.bringToFront();
	}
}
